﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections.Generic;
using System.Linq;
using ScrumTable.Common;
using ScrumTable.Common.Logging;
using ScrumTable.DL.Data.Generic.Cache;
using ScrumTable.DL.Data.Schema;
using ScrumTable.DL.Data.Schema.ScrumTableV1;
using ScrumTable.DL.Data.TFS.Bulk.Properties;
using ScrumTable.DL.Data.TFS.Bulk.Services.IterationHandling.Serialization;
using ScrumTable.DL.Data.TFS.Services.FileSystem;
using ScrumTable.DL.Data.TFS.Services.SharePoint;
using ScrumTable.DL.Data.TFS.Services.TeamFoundation;

using IterationBucket = ScrumTable.DL.Data.Generic.Cache.CacheElementListEntryBucket<ScrumTable.DL.Data.Generic.Cache.CacheIteration>;
using IterationSavePair = ScrumTable.DL.Data.Generic.Cache.CacheSavePair<ScrumTable.DL.Data.Generic.Cache.CacheElementListEntryBucket<ScrumTable.DL.Data.Generic.Cache.CacheIteration>>;

#endregion

namespace ScrumTable.DL.Data.TFS.Bulk.Services.IterationHandling
{
    /// <summary>
    /// This class is used to load all data below a given project.
    /// </summary>
    internal class WssIterationSaver : IterationSaverBase
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new WssIterationSaver with the associated schema config.
        /// </summary>
        /// <param name="schema">Specifies the schema configuration data.</param>
        internal WssIterationSaver(IterationSchema schema)
            : base(schema)
        {
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Stores the iterations to the back-end system.
        /// </summary>
        /// <param name="tfsContext">Specifies the tfs connection information.</param>
        /// <param name="changes">Specifies an instance with the data changes from the data layer.</param>
        internal override void SaveIterationData(TfsServerWrapper tfsContext, CacheDataChanges changes)
        {
            PreCondition.AssertNotNull(tfsContext, "tfsContext");
            PreCondition.AssertNotNull(changes, "changes");

            WssContext sharepointContext = new WssContext(
                changes.Project.ProjectPortal,
                tfsContext.ConnectionInformation);

            if (sharepointContext.IsConnected)
            {
                StoreIterationsIntoWss(sharepointContext, changes);
            }
            else
            {
                StoreIterationsToFs(new FsContext(), changes);
            }
        }


        private void StoreIterationsToFs(FsContext fileSystemContext, CacheDataChanges changes)
        {
            IterationData iterationData = StoreIterationsToFsObjects(fileSystemContext, changes);
            Exception saveError = null;

            try
            {
                fileSystemContext.SetData(changes.Project.OwnerContext.Schema.IterationSchema, iterationData);
            }
            catch (Exception e)
            {
                saveError = e;
                Logger<WssIterationSaver>.Error(Resources.ExcWssIterSaveFailed, e);
            }
            StoreIterationsToFsCompleted(saveError, changes);
        }

        private void StoreIterationsToFsCompleted(Exception e, CacheDataChanges changes)
        {
            foreach (IterationBucket iterBucket in changes.ChangedIterations.Values)
            {
                if (e == null)
                {
                    changes.IterationsToSync[iterBucket.Element.UniqueId].State = CacheSavePairState.Saved;
                }
                else
                {
                    changes.IterationsToSync[iterBucket.Element.UniqueId].Errors.Add(new CacheSaveError(e));
                    changes.IterationsToSync[iterBucket.Element.UniqueId].State = CacheSavePairState.Error;
                }
            }
        }

        private IterationData StoreIterationsToFsObjects(FsContext fileSystemContext, CacheDataChanges changes)
        {
            IterationData iterationData = GetIterationsFromFs(fileSystemContext, changes.Project.OwnerContext.Schema.IterationSchema);
            IDictionary<int, Iteration> iterationDataIdx = iterationData.Iterations.ToDictionary(it => it.IterationId);

            foreach (IterationBucket iterBucket in changes.ChangedIterations.Values)
            {
                if (iterationDataIdx.ContainsKey(iterBucket.Element.Id))
                {
                    iterationDataIdx[iterBucket.Element.Id].IterationId = iterBucket.Element.Id;
                    iterationDataIdx[iterBucket.Element.Id].IterationPathName = iterBucket.Element.Name;
                    iterationDataIdx[iterBucket.Element.Id].EndDate = iterBucket.Element.EndDate;
                    iterationDataIdx[iterBucket.Element.Id].StartDate = iterBucket.Element.StartDate;
                }
                else
                {
                    iterationData.Iterations.Add(new Iteration
                    {
                        IterationId = iterBucket.Element.Id,
                        IterationPathName = iterBucket.Element.Name,
                        EndDate = iterBucket.Element.EndDate,
                        StartDate = iterBucket.Element.StartDate
                    });
                }
            }
            return iterationData;
        }

        private IterationData GetIterationsFromFs(FsContext fileSystemContext, SchemaBase schema)
        {
            IterationData iterationData = fileSystemContext.GetData<IterationData>(schema);
            if (iterationData.Iterations == null)
            {
                iterationData.Iterations = new List<Iteration>();
            }
            return iterationData;
        }


        private void StoreIterationsIntoWss(WssContext sharepointContext, CacheDataChanges changes)
        {
            foreach (IterationBucket iterBucket in changes.ChangedIterations.Values)
            {
                if (TryStoreIteration(sharepointContext, iterBucket))
                {
                    changes.IterationsToSync[iterBucket.Element.UniqueId].State = CacheSavePairState.Saved;
                }
                else
                {
                    changes.IterationsToSync[iterBucket.Element.UniqueId].State = CacheSavePairState.Error;
                }
            }
        }

        private bool TryStoreIteration(WssContext sharepointContext, CacheElementListEntryBucket<CacheIteration> iterBucket)
        {
            try
            {
                WssIteration iteration = sharepointContext.GetIterationOrCreate(
                    iterBucket.Element.Id,
                    iterBucket.Element.Name);

                iteration.EndDate = iterBucket.Element.EndDate;
                iteration.StartDate = iterBucket.Element.StartDate;
                sharepointContext.UpdateIteration(iteration);
                return true;
            }
            catch (Exception e)
            {
                Logger<DataSaveProcess>.Error(
                    string.Format(
                        Resources.ExcDataSaveProcIterSaveFailed,
                        (iterBucket.Element != null) ? iterBucket.Element.Name : string.Empty,
                        (iterBucket.Element != null) ? iterBucket.Element.Id : CacheIdentity.DefaultId),
                    e);
                return false;
            }
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}